#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

const int gsize=1024;
const mode_t gmode=0600;
const std::string gpath="/home/shenyu";
const int projId=6666;

struct MessageBuff
{
    long mtype;   //必须有一个long类型的变量存放消息的类型
    char message[gsize];
};

int main()
{
    //创建消息队列
    key_t key=::ftok(gpath.c_str(),projId);
    if(key<0)
    {
        std::cerr<<"ftok error"<<std::endl;
        return 1;
    }
    //消息队列和共享内存一样也有权限
    int msgid=::msgget(key,IPC_CREAT|IPC_EXCL|gmode);
    if(msgid<0)
    {
        std::cerr<<"msgget error"<<std::endl;
        return 2;
    }
    else 
    {
        std::cout<<"msgget success,msgid:"<<msgid<<std::endl;
    }
    //发送信息
    struct MessageBuff sed;
    sed.mtype=1; //1号类型的数据
    snprintf(sed.message,sizeof(sed.message),"Hello World");
    int n1=msgsnd(msgid,&sed,sizeof(sed.message),0);
    if(n1<0)
    {
        std::cerr<<"msgend error"<<std::endl;
        return 3;
    }

    //接收信息
    struct MessageBuff info;
    info.mtype=1;
    int n2=msgrcv(msgid,&info,sizeof(info.message),1,0);
    if(n2<0)
    {
        std::cerr<<"msgrcv error"<<std::endl;
        return 4;
    }
    else 
    {
        std::cout<<"msgrcv success,message:"<<info.message<<",message type:"<<info.mtype<<std::endl;
    }

    //关闭消息队列
    int n3=msgctl(msgid,IPC_RMID,nullptr);
    if(n3<0)
    {
        std::cerr<<"msgctl error"<<std::endl;
        return 5;
    }
    else 
    {
        std::cout<<"msgctl success"<<std::endl;
    }
    return 0;
}